package com.website.core.aop;

import com.website.common.controller.BaseController;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import java.lang.reflect.Method;

@Aspect
@Component
public class RequestMappingReturnTimeAop extends BaseController {

    private Logger log = LoggerFactory.getLogger(this.getClass());
    //开始时间
    private Long begin;
    //结束时间
    private Long end;
    //用时
    private Long time;

    @Before("@annotation(requestMapping)")
    public void before(RequestMapping requestMapping){
        begin = System.currentTimeMillis();
    }
    @After("@annotation(requestMapping)")
    public void after(RequestMapping requestMapping){
        end = System.currentTimeMillis();
        time = end - begin;
        String returningTime = String.valueOf(time);
        log.info("用时"+returningTime+"毫秒");
    }

    //获取指定的请求的执行时间
    @Pointcut("@annotation(AnnotationAop)")
    public void annotationPointcut() {
    }
    @Before("annotationPointcut()")
    public void beforePointcut() {
        begin = System.currentTimeMillis();
    }

    @After("annotationPointcut()")
    public void afterPointcut(JoinPoint joinPoint){
        MethodSignature methodSignature =  (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        AnnotationAop annotation = method.getAnnotation(AnnotationAop.class);
        String value = annotation.value();
        end = System.currentTimeMillis();
        time = end - begin;
        String returningTime = String.valueOf(time);
        try {
            String methodName = joinPoint.getSignature().getName();
            log.info(methodName+":"+value+"用时"+returningTime+"毫秒");
        }catch (Throwable e){
            throw e;
        }
    }
}
